package com.dux.shiro1.web;

import com.dux.shiro1.web.error.CodeEnum;
import com.dux.shiro1.web.error.RBody;
import com.dux.shiro1.web.util.ShiroUtils;
import com.dux.shiro1.web.vm.UserVM;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * Title: SysResource <br>
 * Description: SysResource <br>
 * Date: 2018年10月22日
 *
 * @author 王东旭
 * @version 1.0.0
 * @since jdk8
 */

@RestController
@RequestMapping("sys")
public class SysResource {

    private static final Logger LOG = LoggerFactory.getLogger(SysResource.class);

    @Autowired
    private Producer producer;

    @GetMapping("login")
    public ResponseEntity login(UserVM user) {
        String attr = ShiroUtils.getAttr(Constants.KAPTCHA_SESSION_KEY);
        if (StringUtils.isBlank(attr)) {
            LOG.info("用户[{}]登陆失败({})",user.getUsername(),CodeEnum.LOGIN_CAPTCHA_TIMEOUT.getMsg());
            return ResponseEntity.badRequest().body(RBody.error(CodeEnum.LOGIN_CAPTCHA_TIMEOUT));
        }
        if (!attr.equals(user.getCaptcha())){
            LOG.info("用户[{}]登陆失败({})",user.getUsername(),CodeEnum.LOGIN_CAPTCHA_ERR.getMsg());
            return ResponseEntity.badRequest().body(RBody.error(CodeEnum.LOGIN_CAPTCHA_ERR));
        }

        try {
            SecurityUtils.getSubject().login(new UsernamePasswordToken(user.getUsername(), user.getPassword(), user.isRememberMe()));
        }catch (IncorrectCredentialsException e){
            LOG.info("用户[{}]登陆失败({})",user.getUsername(),CodeEnum.LOGIN_USER_PASS_ERR.getMsg(),e);
            return ResponseEntity.badRequest().body(RBody.error(CodeEnum.LOGIN_USER_PASS_ERR));
        }catch (AuthenticationException e){
            LOG.info("用户[{}]登陆失败({}).",user.getUsername(),CodeEnum.LOGIN_ERR.getMsg(),e);
            return ResponseEntity.badRequest().body(RBody.error(CodeEnum.LOGIN_USER_PASS_ERR));
        }
        return ResponseEntity.ok(RBody.ok());
    }

    @GetMapping("captcha.jpg")
    public void captchaImg(HttpServletResponse response) throws IOException {

        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setAttr(Constants.KAPTCHA_SESSION_KEY, text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
    }
}
